//
//  LZSelecPicListVC.m
//  DoctorFAQs
//
//  Created by langZai on 2017/3/28.
//  Copyright © 2017年 zjq. All rights reserved.
//

#import "LZSelecPicListVC.h"
#import "LZSelectPicListCell.h"
#import "LZPicModel.h"
#import "ZOnceSubmitViewController.h"
#import "ConsultingDoctorViewController.h"

static NSString * const LZSelectPiclistID = @"lz_selectPiclistID";
@interface LZSelecPicListVC ()<UICollectionViewDelegate,UICollectionViewDataSource> {
    // 照片列表
    UICollectionView *_picListCollectionView;
    LZUserInfo *userInfo;
    LZPicModel * _lzPicModel;
    // 照片数组
    NSMutableArray *_picArray;
    UIButton *_rightBarBtn;
    
}
/** 选中的按钮 */
@property (nonatomic, strong) UIButton *didSelectBtn;
/** 记录选择图片的位置 */
@property (nonatomic, assign) NSInteger picIndexPath;
/** 选中位置的照片大图 */
@property (nonatomic, strong) NSString *img_max;
/** 选中位置照片小图 */
@property (nonatomic, strong) NSString *img_min;
/** 回传照片的字典 */
@property (nonatomic, strong) NSDictionary *returnPicDict;


@end

@implementation LZSelecPicListVC



- (void)viewDidLoad {
    [super viewDidLoad];
    [self initialzeDatas];
    [self initlizeInterface];
    [self makerightButton];
    [_picListCollectionView.mj_header beginRefreshing];
    
    
}


- (void)initialzeDatas {
    userInfo = [LZUserInfo getUserInfo];
    _picArray = [NSMutableArray array];
    _picIndexPath = -1;
    _returnPicDict = [NSDictionary dictionary];
}

- (void)initlizeInterface {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 5;
    layout.itemSize = CGSizeMake(95*xsIZE, 95*ysIZE);
    layout.sectionInset = UIEdgeInsetsMake(5*xsIZE, 5*xsIZE, 5*xsIZE, 5*xsIZE);
    _picListCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_Width, SCREEN_Height) collectionViewLayout:layout];
    _picListCollectionView.backgroundColor = KHColorFromRGB(0xf8f8f8f8);
    _picListCollectionView.showsVerticalScrollIndicator = YES;
    _picListCollectionView.delegate = self;
    _picListCollectionView.dataSource = self;
    
    [_picListCollectionView registerClass:[LZSelectPicListCell class] forCellWithReuseIdentifier:LZSelectPiclistID];
    [self.view addSubview:_picListCollectionView];
    
    __weak typeof(self) weakSelf = self;
    // 下拉刷新
    _picListCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf pullDownData];
        [_picListCollectionView.mj_header endRefreshing];
    }];
}

// 设置右边编辑按钮
- (void)makerightButton {
    _rightBarBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_rightBarBtn setTitle:@"完成" forState:UIControlStateNormal];
    [_rightBarBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    _rightBarBtn.frame = CGRectMake(0, 0, 40, 30);
    [_rightBarBtn addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightButonItem = [[UIBarButtonItem alloc]initWithCustomView:_rightBarBtn];
    self.navigationItem.rightBarButtonItem = rightButonItem;
}

// 点击完成
- (void)rightBtnClick:(UIButton *)btn {
    LZLog(@"完成");
    if (_picIndexPath < 0) {
        [YJProgressHUD showMessage:@"还没有选择照片哦~" inView:self.view];
        return;
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"returnMaxPic" object:nil userInfo:_returnPicDict];
    
    // 跳过中间的页面直接返回选择照片界面
    NSArray *temArray = self.navigationController.viewControllers;
    for(UIViewController *temVC in temArray)
    {
        if ([temVC isKindOfClass:[ConsultingDoctorViewController class]])
        {
            [self.navigationController popToViewController:temVC animated:YES];
        }else if ( [temVC isKindOfClass:[ZOnceSubmitViewController class]])
        {
            [self.navigationController popToViewController:temVC animated:YES];
        }
    }
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _picArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LZSelectPicListCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:LZSelectPiclistID forIndexPath:indexPath];
    cell.lzPicModel = _picArray[indexPath.row];
    
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    //
        LZSelectPicListCell *zcullingCell = (LZSelectPicListCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
        // 只能选择一张照片
        if (_didSelectBtn == zcullingCell.selectBtn) {
            zcullingCell.selectBtn.selected = !zcullingCell.selectBtn.selected;
            return;
        }
        self.didSelectBtn.selected = NO;
        zcullingCell.selectBtn.selected = YES;
        self.didSelectBtn = zcullingCell.selectBtn;
    
    // 记录选中图片的位置
        if (zcullingCell.selectBtn.selected) {
            _picIndexPath = indexPath.row;
            // 在模型中取出对应位置的照片
            for (_lzPicModel in _picArray) {
                _lzPicModel = _picArray[_picIndexPath];
                _img_max = _lzPicModel.img_max;
                _img_min = _lzPicModel.img_min;
         }
    }
    // 把选择type和大图、小图的url传过去
    _returnPicDict = @{@"selecIndex":[NSString stringWithFormat:@"%ld",(long)_selectIndex],@"img_max":_img_max,@"img_min":_img_min};
}
// 下拉刷新
- (void)pullDownData {
    NSDictionary *paramas = @{@"id":self.fileID,@"uid":userInfo.uid,@"type":[NSString stringWithFormat:@"%ld",(long)_selectIndex]};
    __weak typeof(self) weakSelf = self;
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"File/minImg" sucessBlock:^(id content) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        LZLog(@"--------选择图片缩略图列表数据-----------%@",dict);
        if ([dict[@"code"] intValue] == 0) {
            [YJProgressHUD showMessage:@"加载失败" inView:self.view];
        }else if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"加载成功" inView:self.view];
            [weakSelf dealDataWithDict:dict];
            // 保存type
//            _type = dict[@"type"];
        }
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"加载失败" inView:self.view];
    }];
}

// 处理数据拿出照片
- (void)dealDataWithDict:(NSDictionary *)dict {
    [_picArray removeAllObjects];
    NSArray *tempArr = dict[@"list"];
    for (NSDictionary *dict in tempArr) {
        _lzPicModel = [[LZPicModel alloc] initWithDict:[dict mutableCopy]];
        [_picArray addObject:_lzPicModel];
    }
    [_picListCollectionView reloadData];
}


@end
